package com.dy.web.controller.system;

import com.alibaba.fastjson2.JSON;
import com.dy.common.annotation.Log;
import com.dy.common.core.controller.BaseController;
import com.dy.common.core.domain.AjaxResult;
import com.dy.common.core.page.TableDataInfo;
import com.dy.common.enums.BusinessType;
import com.dy.common.utils.StringUtils;
import com.dy.common.utils.poi.ExcelUtil;
import com.dy.system.domain.FreshWarningMsgTypeDetail;
import com.dy.system.domain.MedicalInstitution;
import com.dy.system.domain.WarningMessage;
import com.dy.system.domain.vo.WarningMessageVo;
import com.dy.system.service.IFreshWarningMsgTypeDetailService;
import com.dy.system.service.IMedicalInstitutionService;
import com.dy.system.service.IWarningMessageService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Controller
 *
 * @author anps
 * @date 2022-08-03
 */
@RestController
@RequestMapping("/system/message")
public class WarningMessageController extends BaseController{
    @Autowired
    private IWarningMessageService warningMessageService;
    @Autowired
    private IMedicalInstitutionService medicalInstitutionService;
    @Autowired
    private IFreshWarningMsgTypeDetailService freshWarningMsgTypeDetailService;




    /***
     * 告警信息 applet接口
     * @return
     */
    @GetMapping("/warning/list")
    public AjaxResult getWarningMessageList(Integer status,String searchValue,@RequestParam(required = false) Long medicalId,
                                             Integer pageNo, @RequestParam(required = false,defaultValue = "10") Integer pageSize){

        FreshWarningMsgTypeDetail message = new FreshWarningMsgTypeDetail();
        if (medicalId != null){
            message.setMedicalId(medicalId);
        }
//        if (status != null && status == 1){
//            message.setClearwaterlow("1");
//        }else if (status != null && status == 2){
//            message.setClearwaterhigh("1");
//        }
        message.setWarningType("clearwaterlow");
        if (StringUtils.isNotBlank(searchValue)){
            //查询机构信息
            MedicalInstitution institution = new MedicalInstitution();
            institution.setName(searchValue);
            List<MedicalInstitution> list = medicalInstitutionService.selectMedicalInstitutionList(institution);
            if (!CollectionUtils.isEmpty(list)){
                List<Long> idList = list.stream().map(m -> m.getId()).collect(Collectors.toList());
                message.setMedicalIdList(idList);
            }else{
                message.setCode(searchValue);
            }
        }
        if (pageNo != null && pageSize != null){
            PageHelper.startPage(pageNo,pageSize,"id desc");
        }
        List<FreshWarningMsgTypeDetail> warningMessages = freshWarningMsgTypeDetailService.selectFreshWarningMsgTypeDetailList(message);
        logger.info("warningMessages size ={}",warningMessages.size());
        List<WarningMessageVo> voList = new ArrayList<>();
        warningMessages.forEach(msg -> {
            MedicalInstitution institution = medicalInstitutionService.selectMedicalInstitutionById(msg.getMedicalId());
            if (institution == null){
                return;
            }
            WarningMessageVo vo = new WarningMessageVo();
            vo.setCode(msg.getCode());
                //机构名称
            vo.setMedicalIdName(institution.getName());
            vo.setWarningContent("纯净水位过低");
            vo.setWarningType("clearwaterlow");
            vo.setWarningTime(String.valueOf(msg.getCreateTime().getTime()));
            vo.setStatus(1);
            vo.setRunningStatus(msg.getRunningStatus());
            voList.add(vo);

        });
        return AjaxResult.success(voList);
    }



    /**
     * 查询设备告警信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:message:list')")
    @GetMapping("/list")
    public TableDataInfo list(WarningMessage warningMessage) {
        if (StringUtils.isNotBlank(warningMessage.getMedicalIdName())){
            MedicalInstitution institution = new MedicalInstitution();
            institution.setName(warningMessage.getMedicalIdName());
            List<MedicalInstitution> institutionList = medicalInstitutionService.selectMedicalInstitutionList(institution);
            if (!CollectionUtils.isEmpty(institutionList)){
                List<Long> medicalIdList = institutionList.stream().map(e -> e.getId()).collect(Collectors.toList());
                warningMessage.setMedicalIdList(medicalIdList);
            }
        }
        startPageOrderBy("id desc");
        List<WarningMessage> list = warningMessageService.selectWarningMessageList(warningMessage);
        list.forEach(message ->{
            MedicalInstitution institution = medicalInstitutionService.selectMedicalInstitutionById(message.getMedicalId());
            if (institution != null){
                message.setMedicalIdName(institution.getName());
            }
        });
        return getDataTable(list);
    }

    /**
     * 导出设备告警信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:message:export')")
    @Log(title = "设备告警信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WarningMessage warningMessage) {
        List<WarningMessage> list = warningMessageService.selectWarningMessageList(warningMessage);
        ExcelUtil<WarningMessage> util = new ExcelUtil<WarningMessage>(WarningMessage.class);
        util.exportExcel(response, list, "设备告警信息数据");
    }

    /**
     * 获取设备告警信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:message:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(warningMessageService.selectWarningMessageById(id));
    }

    /**
     * 新增设备告警信息
     */
    @PreAuthorize("@ss.hasPermi('system:message:add')")
    @Log(title = "设备告警信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WarningMessage warningMessage) {
        return toAjax(warningMessageService.insertWarningMessage(warningMessage));
    }

    /**
     * 修改设备告警信息
     */
    @PreAuthorize("@ss.hasPermi('system:message:edit')")
    @Log(title = "设备告警信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WarningMessage warningMessage) {
        return toAjax(warningMessageService.updateWarningMessage(warningMessage));
    }

    /**
     * 删除设备告警信息
     */
    @PreAuthorize("@ss.hasPermi('system:message:remove')")
    @Log(title = "设备告警信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(warningMessageService.deleteWarningMessageByIds(ids));
    }
}
